/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package testmysql;

import java.sql.*;

/**
 *
 * @author NanaCedric
 */
public class TestMySQL {

    private static String connectionUrl = null;
    private static Connection con = null;
    private static Statement stmt = null;

    public static int insert(String table, String[] field, String[] value) throws SQLException {
        String sql = "INSERT INTO " + table + " (";
        String myValues = " VALUES (";

        for (int i = 0; i < field.length; i++) {
            sql += field[i] + ",";
        }
        sql = sql.substring(0, sql.length() - 1) + ")";

        for (int j = 0; j < value.length; j++) {
            myValues += "'" + value[j] + "',";

        }
        myValues = myValues.substring(0, myValues.length() - 1) + ")";

        sql = sql + myValues;
        System.out.println(sql);

        stmt = con.createStatement();
        int id = stmt.executeUpdate(sql);

        return id;
    }

    public static int update(String table, String[] field, String[] value, String condition) throws SQLException {
        String sql = "UPDATE " + table + " SET ";
        String myValue = "";
        for (int i = 0; i < field.length; i++) {
            myValue += field[i] + " = '" + value[i] + "',";
        }
        myValue = myValue.substring(0, myValue.length() - 1);

        sql = sql + myValue + " WHERE " + condition;
        System.out.println(sql);

        stmt = con.createStatement();
        int id = stmt.executeUpdate(sql);

        return id;
    }

    public static void delete(String table, String condition) throws SQLException {
        String del = "DELETE FROM " + table + " WHERE " + condition;
        stmt = con.createStatement();
        stmt.executeUpdate(del);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String field[] = {"name", "age"};
        String value[] = {"yannick", "36"};

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connectionUrl = "jdbc:mysql://localhost/test?" + "user=root";
            con = DriverManager.getConnection(connectionUrl);

            //insert("People", field, value);
            // update("People",field,value, "id = 6");
            delete("People", "id = 9");
        } catch (SQLException e) {
            System.out.println("SQL Exception: " + e.toString());
        } catch (ClassNotFoundException cE) {
            System.out.println("Class Not Found Exception: " + cE.toString());
        }
    }
}
